package io.github.handyang.algorithms.graph;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 邻接矩阵
 */
public class MatrixGraph implements Graph {
    private final byte[][] data;
    private int E = 0;

    public MatrixGraph(int V) {
        this.data = new byte[V][V];

        for (int i = 0; i < data.length; i++) {
            data[i][i] = 1;
        }
    }

    @Override
    public int V() {
        return data.length;
    }

    @Override
    public int E() {
        return E;
    }

    @Override
    public void addEdge(int v, int w) {
        data[v][w] = 1;
        data[w][v] = 1;
        E++;
    }

    @Override
    public Iterable<Integer> adj(int v) {
        List<Integer> res = new ArrayList<>();

        for (int i = 0; i < data[v].length; i++) {
            if (data[v][i] == 1) res.add(i);
        }

        return res;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < this.data.length; i++) {
            builder.append("\n").append(Arrays.toString(this.data[i]));
        }
        return builder.toString();
    }
}
